//
//  TLTimerViewModel.m
//  ReactiveCocoa_Practice
//
//  Created by thinker on 15/8/27.
//  Copyright (c) 2015年 RayTao. All rights reserved.
//

#import "TLTimerViewModel.h"
#import "JX_GCDTimerManager.h"
#import <AudioToolbox/AudioToolbox.h>
#import <ReactiveCocoa/ReactiveCocoa.h>


@interface TLTimerViewModel ()

// Private Access
//@property (nonatomic, strong) ASHRecipe *model;

@property (nonatomic, strong) NSString *recipeName;
@property (nonatomic, strong) NSString *timeRemainingString;
@property (nonatomic, strong) NSString *currentStepString;
@property (nonatomic, strong) NSString *nextStepString;

@property (nonatomic, assign, getter = isRunning) BOOL running;
@property (nonatomic, assign) NSInteger currentStepIndex;
@property (nonatomic, assign) CFTimeInterval currentStepTimeRemaining;

@property (nonatomic, weak) NSString *timer;

@end


@implementation TLTimerViewModel

-(instancetype)init {
    if (self != [super init]) return nil;
    
    self.currentStepIndex = 0;
    self.currentStepTimeRemaining = 60;
    
    // Reactive Bindings
    self.recipeName = @"计时器";

    RAC(self, running) = [RACObserve(self, timer) map:^id(id value) {
        return @(value != nil);
    }];
    
    RAC(self, timeRemainingString) = [RACObserve(self, currentStepTimeRemaining) map:^id(NSNumber *value) {
        NSInteger duration = [value integerValue];
        NSInteger minutes = duration / 60;
        NSInteger seconds = duration % 60;
        return [NSString stringWithFormat:@"%ld:%02ld", (long)minutes, (long)seconds];
    }];

    
    return self;
}

#pragma mark - Public Methods

-(void)pause {
    [[JX_GCDTimerManager sharedInstance] cancelTimerWithName:self.timer];
}

-(void)resume {
    [[JX_GCDTimerManager sharedInstance] scheduledDispatchTimerWithName:self.timer timeInterval:1.0 queue:dispatch_get_main_queue() repeats:YES action:^{
        [self clockTick];
    }];
}

#pragma mark - Private Methods

-(void)clockTick {
    self.currentStepTimeRemaining--;
    
    if (self.currentStepTimeRemaining < 0) {
        self.currentStepIndex++;
        
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        
//        if (self.currentStepIndex >= self.model.steps.count) {
//            [self pause];
//        } else {
//            self.currentStepTimeRemaining = [(ASHStep *)[[self.model steps] objectAtIndex:self.currentStepIndex] duration];
//        }
    }
    
}

- (NSString *)timer {
    return self.description;
}

@end
